package com.ngkj.zmfptback.sys.util;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ngkj.zmfptback.sys.bean.UserEntity;
import com.ngkj.zmfptback.sys.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author ChenHN
 * @since 2021/12/1 creation
 **/
@Slf4j
public class JwtTokenUtil {

    private JwtTokenUtil(){}


    public static String createAccessToken(UserEntity userEntity){

        // 登陆成功生成JWT
        String token = Jwts.builder()
                // 放入用户名和用户ID
                .setId(userEntity.getId()+"")
                // 主题
                .setSubject(userEntity.getUsername())
                // 签发时间
                .setIssuedAt(new Date())
                // 签发者
                .setIssuer("ng")
                // 自定义属性 放入用户拥有权限
                .claim("authorities", JSON.toJSONString(userEntity.getAuthorities()))
                // 失效时间
                .setExpiration(new Date(System.currentTimeMillis() + JwtConfig.expiration))
                // 签名算法和密钥
                .signWith(SignatureAlgorithm.HS512, JwtConfig.secret)
                .compact();
        return token;
    }

    public static Map<String,Object> getUserInfo(String token){
        Map<String,Object> map = new HashMap<>();
        // 解析jwt
        Claims claims = Jwts.parser()
                .setSigningKey(JwtConfig.secret)
                .parseClaimsJws(token)
                .getBody();
        //获取用户名
        String id = claims.getId();
        List<SimpleGrantedAuthority> authorities = null;
        String authority = claims.get("authorities").toString();
        if (!StringUtils.isEmpty(authority)) {
            authorities = JSON.parseArray(authority, SimpleGrantedAuthority.class);
        }
        map.put("id",id);
        List<String> roleList = new ArrayList<>();
        authorities.forEach(item->{
            roleList.add(item.getAuthority());
        });
        map.put("roleList",roleList);
        return map;
    }

}
